package org.teamh.gui.engine.model;

import java.io.File;
import java.net.URISyntaxException;
import java.net.URL;

/**
 * This class is responsible for loading the models Currently, only obj format
 * is supported.
 * 
 * @author richard
 * 
 */
public class ModelLoader {
	
	/**
	 * Returns a model with the specified file name. 
	 * @param fileName
	 * @return
	 */
	public static Model getModel(String fileName) {
		URL url = ModelLoader.class.getClassLoader().getResource(fileName);

		File file = null;
		if (url != null) {
			try {
				file = new File(url.toURI());
			} catch (URISyntaxException e) {
				e.printStackTrace();
			}
		}

		if (file == null) {
			file = new File(fileName);
		}

		if (!file.exists()) {
			System.out.println("Model " + fileName + " not found");
			return null;
		}

		return getModel(file);
	}
	
	/**
	 * Returns a model, which is in the file. 
	 * @param file
	 * @return
	 */
	public static Model getModel(File file) {
		String ext = getExtension(file).toLowerCase();
		
		if(ext.equals("obj")) {
			return OBJLoader.getOBJ(file);
		} 
		
		System.out.println("This file format is not supported: " + file);
		
		return null;
	}

	/**
	 * This method returns any file, which is in connection with the current
	 * model like texture files or material files.
	 * 
	 * @param file
	 * @return
	 */
	public static File[] getFiles(File file) {
		String ext = getExtension(file).toLowerCase();
		
		if(ext.equals("obj")) {
			return OBJLoader.getOBJFiles(file);
		} else {
			System.out.println("Not a valid file type");
		}
		
		return null;
	}
	
	/**
	 * Returns the extension of a file f. 
	 * @param f
	 * @return
	 */
	private static String getExtension(File f) {
		String ext = null;
        String s = f.getName();
        int i = s.lastIndexOf('.');

        if (i > 0 &&  i < s.length() - 1) {
            ext = s.substring(i+1).toLowerCase();
        }
        return ext;
	}
	
	/**
	 * Removes all the models from the graphics card. 
	 */
	public static void dealloc() {
		OBJLoader.dealloc();
	}
}
